﻿using CoachingOrganizer.ClientInfrastructure.ServicesEntities.LocalStorage.Tools.MoneyCalculation;
using CoachingOrganizer.Logic.Common;
using CoachingOrganizer.Logic.Models.Tools.MoneyCalculation;
using CoachingOrganizer.Toolkit.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CoachingOrganizer.Logic.Logic.Tools.MoneyCalculation
{
    internal class StableMoneyFlowItemLogic
    {
        private readonly StableMoneyFlowItemModel _model;
        private readonly LogicExtender _logicExtender;
        private readonly MoneyFlowLogic _upperLogic;
        private readonly IStableMoneyFlowItemInfo _localData;
        
        public StableMoneyFlowItemModel Model
        {
            get { return _model; }
        }

        public IStableMoneyFlowItemInfo LocalData
        {
            get { return _localData; }
        } 

        public StableMoneyFlowItemLogic(StableMoneyFlowItemModel model, LogicExtender logicExtender, MoneyFlowLogic upperLogic, IStableMoneyFlowItemInfo localData)
        {
            _model = model;
            _logicExtender = logicExtender;
            _upperLogic = upperLogic;
            _localData = localData;
            model.RemoveDelegate = Remove;
            model.SaveDelegate = Save;
        }

        public decimal GetPeriodAmount(DateTime start, DateTime finish)
        {
            int periodsCount;
            DateTime correctedStart = _model.Start > start ? _model.Start : start;
            DateTime correctedFinish = _model.Finish < finish ? _model.Finish : finish;
            if (_model.GetIsYearPeriod())
                periodsCount = correctedFinish.Year - correctedStart.Year;
            if (_model.GetIsMonthPeriod())
                periodsCount = (correctedFinish.Year - correctedStart.Year) * 12 + correctedFinish.Month - correctedStart.Month;
            else
                periodsCount = (int)Math.Floor((correctedFinish - correctedStart).TotalDays / _model.Period.TotalDays);
            return periodsCount > 0 ? periodsCount * _model.Amount : (decimal)((correctedFinish - correctedStart).TotalDays / _model.Period.TotalDays * (double)_model.Amount);
        }

        private ActionResult Remove()
        {
            return _upperLogic.RemoveStableItem(this);
        }

        private ActionResult Save()
        {
            _localData.Start = _model.Start;
            _localData.Finish = _model.Finish;
            _localData.Name = _model.Name;
            _localData.Period = _model.Period;
            _localData.Amount = _model.Amount;
            return _localData.Save();
        }
    }
}
